package com.distributed.netty.server;

import com.distributed.netty.entity.ElementJob;
import com.rcache.core.cache.Rcache;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.log4j.Logger;

import java.util.LinkedList;


/**
 * @desc	服务端	
 * @author	高增源
 * @time	2022-05-08
 */
public class Server extends Thread {
	LinkedList<ElementJob> jobList=new LinkedList<>();
	Rcache rcache;
	Logger LOG=Logger.getLogger(Server.class);
	public Server(Rcache rcache) {
		this.rcache = rcache;
	}

	/**
	 * @desc 添加job
	 * @param elementJob
	 */
	public void addJob(ElementJob elementJob){
		jobList.add(elementJob);
	}

	public void init() {
		try {
			LOG.debug("服务端已启动");
			EventLoopGroup boss =new NioEventLoopGroup();
			EventLoopGroup worker =new NioEventLoopGroup();
			ServerBootstrap serverBootstrap=new ServerBootstrap();
			serverBootstrap.group(boss,worker)
					.channel(NioServerSocketChannel.class)
					//回调手柄
					.childHandler(new HeartBeatServerInitializer(rcache,jobList));
			//同步的开
			ChannelFuture con = serverBootstrap.bind(rcache.getDistributePort()).sync();

			con.channel().closeFuture().sync();
			boss.shutdownGracefully().sync();
			worker.shutdownGracefully().sync();
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		LOG.debug("master线程已启动……");
		init();
	}
}
